
/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.datagather.twitter.acount;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.tompai.datagather.model.TwitterAcounts;
import com.tompai.datagather.twitter.InvalidQueryException;
import com.tompai.datagather.twitter.ShadowSockets5Proxy;

/**
 * @desc: datagather-tools
 * @name: TwitterFollowSearch.java
 * @author: tompai
 * @createTime: 2018年5月7日 下午11:46:45
 * @history:
 * @version: v1.0
 */

public abstract class TwitterFollowSearch {

	public static final Logger LOG = LoggerFactory.getLogger(TwitterFollowSearch.class);

	public final static String SCROLL_CURSOR_PARAM = "max_position";
	public final static String TWITTER_HOME_URL = "https://twitter.com";

	public TwitterFollowSearch() {

	}

	public abstract boolean saveTacounts(final String acount, final String role, List<TwitterAcounts> tweetBeans);

	public void searchFollow(final String acount, final String role, final long rateDelay)
			throws InvalidQueryException {
		
		FollowersResponse response;
		List<TwitterAcounts> acounts = TwitterFollowInfo.initialFollow(acount, role);
		if(acounts==null) {
			return;
		}
		String position = TwitterFollowInfo.getPosition();
		//LOG.info("position: " + position);
		saveTacounts(acount, role, acounts);
		boolean isSecurity = TwitterFollowInfo.isSecurity;
		boolean isErrorPage = TwitterFollowInfo.isErrorPage;
		URL url = constructFollowURL(acount, role, position);
		boolean continueSearch = true;
		while (!isErrorPage 
				&& !isSecurity 
				&& (response = executeFollowSearch(url)) != null 
				&& continueSearch
				&& !response.getTweets().isEmpty()) {

			continueSearch = saveTacounts(acount, role, response.getTweets());
			position = response.getMin_position();
			// LOG.info("Position :" + position);
			if (!StringUtils.isEmpty(position) && !position.equals("0")) {
				// PseasNetUtils.sleep(7 * 1000);
				String maxPosition = position;
				url = constructFollowURL(acount, role, maxPosition);
				//LOG.info("Search URL:" + url.toString());
			} else {
				LOG.info("Position :" + "Empty.");
				break;
			}
		}
		LOG.info(acount+" : "+role+" finished.");
	}

	public static FollowersResponse executeFollowSearch(final URL url) {
		
		try {
			//LOG.info("Connnect the url: "+url.toString());   
			Thread.sleep(3 * 1000);
			String content = ShadowSockets5Proxy.twitterLink(url.toString());
			Gson gson = new Gson();
			return gson.fromJson(content, FollowersResponse.class);
		} catch (InterruptedException e2) {
			e2.printStackTrace();
		} catch (Exception e) {
			// If we get an IOException, sleep for 5 seconds and retry.
			LOG.error("Could not connect to Twitter. Retrying in 5 seconds.");
			try {
				Thread.sleep(30 * 1000);
				return executeFollowSearch(url);
			} catch (InterruptedException e2) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// the twitter homepage some follow page;
	public static URL constructFollowURL(final String acount, final String role, final String maxPosition)
			throws InvalidQueryException {
		if (acount == null || acount.isEmpty()) {
			throw new InvalidQueryException(acount);
		}
		try {
			URIBuilder uriBuilder;
			uriBuilder = new URIBuilder(
					TWITTER_HOME_URL + "/" + acount + "/" + role + "/users?include_available_features=1");
			uriBuilder.addParameter("include_entities", "1");
			uriBuilder.addParameter("reset_error_state", "false");
			if (maxPosition != null) {
				uriBuilder.addParameter(SCROLL_CURSOR_PARAM, maxPosition);
			}
			return uriBuilder.build().toURL();
		} catch (MalformedURLException | URISyntaxException e) {
			e.printStackTrace();
			throw new InvalidQueryException(acount);
		}
	}
}
